package com.zee.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zee.admin.dao.SysMenuDao;
import com.zee.admin.dao.SysRoleDataScopeDao;
import com.zee.admin.dao.SysUserDao;
import com.zee.admin.dao.SysUserTokenDao;
import com.zee.admin.entity.SysUser;
import com.zee.admin.entity.SysUserToken;
import com.zee.admin.enums.SuperAdminEnum;
import com.zee.admin.service.IShiroService;
import com.zee.admin.shiro.AdminUserDetail;
import com.zee.common.redis.RedisKeys;
import com.zee.common.redis.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ShiroServiceImpl implements IShiroService {
    @Value("${zee.redis.open: false}")
    private boolean isOpenRedis;

    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserTokenDao sysUserTokenDao;
    @Autowired
    private SysRoleDataScopeDao sysRoleDataScopeDao;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Set<String> getUserPermissions(AdminUserDetail user) {
        List<String> permissionsList;
        if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) {
            //系统管理员，拥有最高权限，返回所有sysmenu表的权限，意味着所有权限标识都要添加进表admin才有对应的权限
            permissionsList = sysMenuDao.getPermissionsList();
        } else {
            permissionsList = sysMenuDao.getUserPermissionsList(user.getId());
        }

        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String permissions : permissionsList) {
            if (StringUtils.isBlank(permissions)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(permissions.trim().split(",")));
        }

        return permsSet;
    }

    @Override
    public SysUserToken getByToken(String token) {
        SysUserToken sysUserToken = null;
        //开启redis从缓存中查
        if (isOpenRedis) {
            String tokenInfo = (String) redisUtil.get(RedisKeys.getAdminUserToken(token));
            if (tokenInfo != null) {
                sysUserToken = JSONObject.parseObject(tokenInfo, SysUserToken.class);
            }
        } else {
            sysUserToken = sysUserTokenDao.getByToken(token);
        }
        return sysUserToken;
    }

    @Override
    public SysUser getUser(Integer userId) {
        return sysUserDao.selectById(userId);
    }

    @Override
    public List<Integer> getDataScopeList(Integer userId) {
        return sysRoleDataScopeDao.getDataScopeList(userId);
    }
}